<template>
  <div v-show="isShowPage">
    <template v-if="total">
      <!-- filter -->
      <el-form class="form" :model="search" :inline="true" size="mini">
        <div class="form-btn">
          <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
          <el-button size="mini" @click="handleReset">清空</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :md="5" :sm="7">
            <el-form-item>
              <el-autocomplete
                v-model="search.estate"
                :fetch-suggestions="loadSearchEstate"
                placeholder="请输入小区名称"
                @select="handleSelectSearchEstate"
                clearable
                @clear="handleEstateClear"
                @input="handleEstateInput"
              ></el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="12">
            <el-form-item>
              <el-date-picker
                v-model="search.updateTime"
                type="daterange"
                range-separator="至"
                start-placeholder="更新日期"
                end-placeholder="更新日期"
                :editable="false"
                value-format="timestamp"
                :default-time="['00:00:00', '23:59:59']"
                @change="handleDateClear"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :md="5">
            <el-form-item>
              <el-select v-model="search.houseSalesStatus" placeholder="房源状态">
                <el-option
                  v-for="dict in houseSalesStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- list -->
      <div class="list">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          header-cell-class-name="list-header"
          size="mini"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column
            v-for="item in tableOptions"
            :key="item.id"
            :label="item.label"
            :prop="item.prop"
            :width="item.width"
            :min-width="item.minWidth"
          >
            <template slot-scope="{ row }">
              <span v-if="item.prop">{{ row[item.prop] }}</span>

              <template v-if="item.id == 'TAB_INFO'">
                <HouseListItemBase :row="row" @clickTag="handleTagClick" @clickTitle="handleEdit"></HouseListItemBase>
              </template>

              <div v-if="item.id == 'TAB_TIME'">{{ row.updateTime }} ({{ row.updateDateInterval }})</div>

              <div v-if="item.id == 'TAB_CONTROL'">
                <span class="text-blue pointer mr10" @click="handleError(row.id)">完善房源</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="gap-h60"></div>

      <!-- 操作 -->
      <div class="control" :style="{ left: sidebar.opened ? '210px' : '54px' }">
        <el-checkbox isIndeterminate v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <el-button
          class="ml30"
          size="small"
          plain
          :disabled="!(tableSelect && tableSelect.length)"
          @click="handleDelete"
          >删除</el-button
        >
        <el-button
          v-if="search.houseSalesStatus === 'UNAVAILABLE'"
          size="small"
          plain
          :disabled="!(tableSelect && tableSelect.length)"
          @click="handlePutUpDown"
          >上架</el-button
        >
        <el-button
          v-if="search.houseSalesStatus === 'AVAILABLE'"
          size="small"
          plain
          :disabled="!(tableSelect && tableSelect.length)"
          @click="handlePutUpDown"
          >下架</el-button
        >
        <div class="fr">
          <el-pagination
            :total="search.pageTotal"
            :page-size="search.pageSize"
            :current-page="search.pageIndex"
            :page-sizes="[10, 20, 30, 50]"
            layout="prev, pager, next, jumper, total, sizes"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"
            background
          >
          </el-pagination>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="empty">
        <el-image style="width: 280px; height: 176px;" :src="require('@/assets/images/list_empty@1x.png')"></el-image>
        <div class="mt30">您暂时不存在异常房源～</div>
      </div>
    </template>

    <!-- success dialog -->
    <el-dialog class="result-dialog" :visible.sync="isShowSuccessDialog" center :show-close="false" width="640px">
      <div class="result">
        <el-image style="width: 240px; height: 160px;" :src="require('@/assets/images/list_success@1x.png')"></el-image>
        <div class="mt30">该套房源异常已经全部处理完毕，已经进入可发房源列表~</div>
        <el-button class="result-btn" type="primary" round @click="handlePublish">立即推送</el-button>
        <el-button class="result-btn-cancel" type="text" @click="isShowSuccessDialog = false">返回列表</el-button>
      </div>
    </el-dialog>

    <!-- fail dialog -->
    <el-dialog class="result-dialog" :visible.sync="isShowFailDialog" center :show-close="false" width="640px">
      <div class="result">
        <el-image style="width: 240px; height: 160px;" :src="require('@/assets/images/list_warn@1x.png')"></el-image>
        <div class="mt30">该套房源还存在部分异常未处理，推送端口会造成违规~</div>
        <el-button class="result-btn" type="primary" round @click="handleRsultFailConfirm">继续处理</el-button>
        <el-button class="result-btn-cancel" type="text" @click="isShowFailDialog = false">返回列表</el-button>
      </div>
    </el-dialog>

    <!-- err handler dialog -->
    <template v-if="excVisible">
      <ComExceptionPop
        :delId="currentControlData.delId"
        :excVisible.sync="excVisible"
        type="exception"
        from="fail"
        @handleResult="handleErrorChange"
      ></ComExceptionPop>
    </template>

    <!-- edit dialog -->
    <template v-if="isShowEditDialog">
      <ComExceptionPop
        :delId="currentControlData.delId"
        :excVisible.sync="isShowEditDialog"
        :tab="currentControlData.tab"
        :type="currentControlData.type || 'edit'"
        from="fail"
        @change="handleHouseChange"
      ></ComExceptionPop>
    </template>
  </div>
</template>

<script>
import HouseListItemBase from './HouseListItemBase';
import ComExceptionPop from '../../ComExceptionPop';

import { scrollTo } from '@/utils/scroll-to';
import { getPushAblePortList } from '@/handler/menuHandler';
import { mapGetters } from 'vuex';

export default {
  name: 'PublishHouseFailList',

  components: {
    HouseListItemBase,
    ComExceptionPop
  },

  props: {
    total: {
      type: Number,
      default: 0
    },
    portInfoPromise: {}
  },

  data() {
    this.checkTimer = null;
    this.houseSalesStatusOptions = [
      { dictValue: 'AVAILABLE', dictLabel: '在售房源' },
      { dictValue: 'UNAVAILABLE', dictLabel: '下架房源' }
    ];
    return {
      isShowPage: false,
      excVisible: false,
      isShowSuccessDialog: false,
      isShowFailDialog: false,
      isShowEditDialog: false,
      loading: false,
      search: {
        pageTotal: 0,
        pageIndex: 1,
        pageSize: 10,
        estate: '',
        estateId: '',
        updateTime: [],
        houseSalesStatus: 'AVAILABLE'
      },
      tableOptions: [
        { id: 'TAB_INFO', label: '基础信息', minWidth: '300' },
        { id: 'TAB_TIME', label: '更新时间', minWidth: '300' },
        { id: 'TAB_CONTROL', label: '操作', width: '200' }
      ],
      tableSelect: [],
      tableData: [],
      currentControlData: {}
    };
  },

  computed: {
    ...mapGetters(['sidebar'])
  },

  watch: {
    tableSelect: {
      handler: function(val) {
        if (val && val.length && val.length === this.tableData.length) {
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      },
      immediate: true,
      deep: true
    }
  },

  beforeMount() {},

  mounted() {
    this.pushList(1, true);
  },

  beforeDestroy() {
    this.clearTimer('checkTimer');
  },

  methods: {
    // ------------------handle------------------
    // 搜索列表
    handleSearch() {
      this.pushList(1);
    },
    // 重置全部筛选
    handleReset() {
      this.search.estate = '';
      this.search.estateId = '';
      this.search.updateTime = [];
      this.search.houseSalesStatus = 'AVAILABLE';
      this.pushList(1);
    },
    // 清除日期筛选
    handleDateClear(e) {
      if (e === null) {
        this.pushList(1);
      }
    },
    // 搜索小区
    handleEstateInput() {
      if (this.search.estateId) {
        this.search.estateId = '';
      }
    },
    // 选择小区
    handleSelectSearchEstate(e) {
      this.search.estateId = e.id || '';
      this.search.estate = e.value || '';
    },
    // 切换分页size
    handlePageSizeChange(e) {
      this.search.pageSize = e;
      this.pushList(1);
      scrollTo(0, 800);
    },
    // 切换分页index
    handleCurrentChange(e) {
      this.pushList(e);
    },
    // 清除小区
    handleEstateClear() {
      this.search.estate = '';
      this.search.estateId = '';
      this.pushList(1);
    },
    // 编辑房源
    handleEdit(id) {
      this.currentControlData = { delId: id };
      this.isShowEditDialog = true;
    },
    // 保存编辑
    handleHouseChange() {
      this.pushList(null, true);
      this.$emit('countChange');
      this.currentControlData = {};
    },
    // 完善房源
    handleError(id) {
      this.checkPort()
        .then(() => {
          if (id) {
            this.currentControlData = { delId: id };
          }
          this.excVisible = true;
        })
        .catch(() => {
          console.log('未绑定端口');
        });
    },
    // 保存完善房源
    handleErrorChange(e) {
      if (e.type === 'success') {
        this.resultSuccess();
      }
      if (e.type === 'error') {
        this.resultFail();
      }
    },
    // 继续完善房源
    handleRsultFailConfirm() {
      this.isShowFailDialog = false;
      this.handleError();
    },
    // 立即推送
    handlePublish() {
      const { delId } = this.currentControlData;
      this.$emit('publish', { data: [delId], handler: this.publishSuccess.bind(this) });
      this.isShowSuccessDialog = false;
    },
    // 多选
    handleSelectionChange(e) {
      this.tableSelect = e.map((item) => item.id);
    },
    // 全选
    handleCheckAllChange() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    // 批量上下架
    async handlePutUpDown() {
      try {
        const { tableSelect } = this;
        const { houseSalesStatus } = this.search;
        this.$confirm(`您确定要${houseSalesStatus === 'AVAILABLE' ? '下架' : '上架'}房源?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(async () => {
            let res = await this.$api.downDelAndHmCooperationHouse({
              delId: tableSelect.join(),
              state: houseSalesStatus === 'AVAILABLE' ? 'UNAVAILABLE' : 'AVAILABLE',
              invalidType: '1'
            });
            if (res && res.isSuccess) {
              this.$alert(res.content.msg, '提示', {
                showClose: false,
                confirmButtonText: '确定'
              });
            } else {
              this.$alert(`${houseSalesStatus === 'AVAILABLE' ? '下架' : '上架'}失败,请稍后再试!`, '提示', {
                showClose: false,
                confirmButtonText: '确定'
              });
            }
            this.pushList(1);
          })
          .catch(() => {});
      } catch (error) {
        console.log('error', error);
      }
    },
    // 批量删除
    async handleDelete() {
      try {
        this.$confirm('是否确认删除房源?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(async () => {
            let res = await this.$api.deleteHouseByIds({
              ids: this.tableSelect
            });
            if (res && res.isSuccess && res.content) {
              this.$message.success(`已成功删除${res.content.successCount}套，失败${res.content.errorCount}套`);
              this.pushList(1);
            } else {
              this.$message.error('删除失败，请稍后再试~');
            }
          })
          .catch(() => {});
      } catch (error) {}
    },
    // 点击标签
    handleTagClick(e) {
      this.currentControlData = { delId: e.delId, type: 'resource', tab: e.tab };
      this.isShowEditDialog = true;
    },
    // ------------------function------------------
    // 加载房源列表
    async pushList(currentIndex, stopScroll = false) {
      try {
        this.clearTimer('checkTimer');
        this.loading = true;
        const { pageIndex, pageSize, estate, estateId, updateTime, houseSalesStatus } = this.search;
        const params = {
          resblockId: estateId || null,
          resblockName: estateId ? null : estate || null,
          updateStartTime: (updateTime && updateTime[0]) || null,
          updateEndTime: (updateTime && updateTime[1]) || null,
          pushFlag: '1',
          currentPage: currentIndex || pageIndex,
          pageSize: pageSize,
          delegationType: 'SALES',
          portType: await getPushAblePortList(),
          state: houseSalesStatus
        };
        const res = await this.$api.pushList(params);
        if (res && res.isSuccess && res.content) {
          let result = res.content || {};
          this.search.pageIndex = params.currentPage;
          this.search.pageTotal = result.total || 0;
          this.tableData = result.records || [];
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.loading = false;
        this.isShowPage = true;
        if (!stopScroll) {
          scrollTo(0, 800);
        }
      }
    },
    // 加载小区列表
    async loadSearchEstate(query, cb) {
      try {
        if (!(query && query.trim())) {
          cb([]);
          return;
        }
        let res = await this.$api.likeResblockName({
          keyWord: query,
          page: 1,
          pageSize: 40
        });
        let result = res.content.rows.map((item) => {
          return { value: item.resblockName, id: item.resblockId };
        });
        cb(result);
      } catch (error) {
        cb([]);
        console.log('error', error);
      }
    },
    // 校验推送端口
    checkPort() {
      return new Promise((resolve, reject) => {
        this.portInfoPromise.then((hasPort) => {
          if (!hasPort) {
            this.$emit('portError');
            return reject();
          }
          resolve();
        });
      });
    },
    // 处理完善房源成功
    resultSuccess() {
      this.isShowSuccessDialog = true;
      this.$emit('countChange');
      this.pushList(null, true);
    },
    // 处理完善房源失败
    resultFail() {
      this.isShowFailDialog = true;
    },
    // 处理推送成功
    publishSuccess() {
      this.$confirm('房源发布任务提交成功，您可以前往发布日志查看结果', '提示', {
        confirmButtonText: '前往查看',
        cancelButtonText: '继续处理异常',
        type: 'success'
      })
        .then(() => {
          this.$router.push({
            name: 'log'
          });
        })
        .catch(() => {
          this.pushList(null, true);
        });
    },
    // 收集列表tag下载中状态的数据
    getListByPending() {
      const { tableData } = this;
      let list = tableData.filter((item) => {
        return item.videoStatus === '1' || item.sphereStatus === '1' || item.houSubTypeState === '1';
      });
      let formatList = list.map((item) => {
        return {
          delId: item.id,
          houSubTypeState: item.houSubTypeState,
          sphereStatus: item.sphereStatus,
          videoStatus: item.videoStatus
        };
      });
      return formatList;
    },
    // 对比列表tag是否变化
    diffTagStatus(oldList, newList) {
      let tag = ['houSubTypeState', 'sphereStatus', 'videoStatus'];
      let flag = {
        change: false,
        unfinished: false
      };
      oldList.forEach((item, index) => {
        tag.forEach((tagItem) => {
          if (newList[index] && newList[index][tagItem] === '1') {
            flag.unfinished = true;
          }
          if (newList[index] && newList[index][tagItem] !== item[tagItem]) {
            flag.change = true;
          }
        });
      });
      return flag;
    },
    // 刷新列表tag状态
    async checkTagStatus() {
      try {
        let param = this.getListByPending();
        if (!(param && param.length)) {
          return;
        }
        this.checkTimer = setInterval(async () => {
          let res = await this.$api.pushListStatus(param);
          let diff = this.diffTagStatus(param, res.content);
          if (!diff.unfinished) {
            this.clearTimer('checkTimer');
          }
          if (diff.change) {
            this.pushList(0, true);
          }
        }, 10000);
      } catch (error) {
        console.log('error', error);
      }
    },
    // 清除定时器
    clearTimer(name) {
      if (this[name]) {
        clearInterval(this[name]);
        clearTimeout(this[name]);
        this[name] = null;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.form {
  position: relative;
  margin: 20px 20px 0;
  padding: 20px 120px 5px 20px;
  border-radius: 10px;
  background-color: #fff;

  .form-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 1;
  }
}

.list {
  margin: 20px;
  padding: 20px;
  border-radius: 10px;
  background-color: #fff;

  & /deep/ .el-table::before {
    height: 0;
  }

  & /deep/ .list-header {
    height: 56px;
    color: #213654;
    background-color: #dfecff;
  }

  & /deep/ .el-table__header .el-table-column--selection .cell {
    display: none;
  }

  & /deep/ .el-table td {
    border: none;
  }

  & /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
    background-color: #f8fbff;
  }
}

.control {
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 0 40px;
  height: 60px;
  background-color: #fff;
  z-index: 1;
  transition: all 0.3s;
}

.empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 124px);

  .empty-btn {
    margin-top: 40px;
    width: 240px;
    height: 48px;
    border-radius: 999px;
    padding: 0;
    font-weight: 700;
  }
}

.result-dialog /deep/ .el-dialog {
  border-radius: 20px;
}

.result {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .result-btn {
    margin-top: 40px;
    width: 240px;
    height: 48px;
    border-radius: 999px;
    padding: 0;
    font-weight: 700;
  }

  .result-btn-cancel {
    margin: 20px 0 0;
    font-weight: 700;
  }
}

.gap-h60 {
  height: 60px;
}
</style>
